<script setup>
import { ref, nextTick } from 'vue'
import { channelAddCateService, channelUpdateCateService } from '@/api/channel'
const channelFrom = ref({
  cateName: '',
  cateAlias: ''
})
const channelRules = {
  cateName: [
    { required: true, message: '分类名称不能为空', trriger: 'blur' },
    { pattern: /^\S+$/, message: '分类名称为非空字符', trriger: 'blur' }
  ],
  cateAlias: [
    { required: true, message: '分类名称不能为空', trriger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,}$/,
      message: '分类名称为非空字符',
      trriger: 'blur'
    }
  ]
}
const isVisiable = ref(false)
const title = ref('')
const channelFormRef = ref(null)
// 暴露方法供外面调用
const open = async (channelProfile) => {
  isVisiable.value = true
  // console.log(channelProfile)
  if (!channelProfile?.id) {
    title.value = '添加分类'
    await nextTick() // 等待 DOM 更新，确保表单完全渲染
    channelFormRef?.value.resetFields()
    // console.log('执行添加操作')
  } else {
    title.value = '编辑分类'
    channelFrom.value.cateName = channelProfile.cate_name
    channelFrom.value.cateAlias = channelProfile.cate_alias
    channelFrom.value.id = channelProfile.id
    // console.log('执行编辑操作')
  }
}
defineExpose({ open })
const emit = defineEmits(['submitMessage'])
const handleCommit = async () => {
  if (title.value === '添加分类') {
    const res = await channelAddCateService(channelFrom.value)
    isVisiable.value = false
    emit('submitMessage', res.message)
  } else {
    const res = await channelUpdateCateService(channelFrom.value)
    isVisiable.value = false
    emit('submitMessage', res.message)
  }
}
</script>
<template>
  <div>
    <el-dialog v-model="isVisiable" width="400" align-center>
      <template #header>{{ title }}</template>
      <el-form :model="channelFrom" :rules="channelRules" ref="channelFormRef">
        <el-form-item label="分类名称" prop="cateName">
          <el-input
            v-model="channelFrom.cateName"
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="分类别名" prop="cateAlias">
          <el-input
            v-model="channelFrom.cateAlias"
            placeholder="请输入分类别名"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleCommit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped></style>
